/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.services.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class UpdaterServlet
 */
public class RecommendationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RecommendationServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    PrintWriter pw = response.getWriter();
	    response.setContentType("text/html");
        pw.print("<html><head/><body><h1>Your name is </h1></body></html>");
	}

//	/**
//	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
//	 */
//	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//	    try {
//	        
//	        final String param = request.getParameter("ac");
//            if("e".equalsIgnoreCase(param)) {//enhance
//                goEnhance(request, response);
//                return;
//            } else if("ig".equalsIgnoreCase(param)) {//image gallery
//                goImageGallery(request, response);
//                return;
//            } else if("d".equalsIgnoreCase(param)) {//download content
//                goDownload(request, response);
//                return;
//            } else if("os".equalsIgnoreCase(param)) {//open search
//                goOpenSearch(request, response);
//                return;
//            } else if("sn".equalsIgnoreCase(param)) {//search by name
//                goSearchByName(request, response);
//                return;
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//	}
//	
//	private void goDownload(HttpServletRequest request, HttpServletResponse response) {
//        try{
//            ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
//            
//            String what = request.getParameter("w");
//            if("bg".equalsIgnoreCase(what)) {
//                System.out.println("Group download requested...");
//                List<BusinessGroupItem> list = new ArrayList<BusinessGroupItem>();
//                BusinessGroupItem bg = new BusinessGroupItem(1, "Food");
//                bg.add(new BusinessItem(1, 1, 1, "pizza", "Pizza", false));
//                bg.add(new BusinessItem(1, 2, 2, "restaurant", "Restaurants", false));
//                bg.add(new BusinessItem(1, 3, 3, "hotdog", "Hot-Dogs", false));
//                list.add(bg);
//                
//                bg = new BusinessGroupItem(2, "Drinks");
//                bg.add(new BusinessItem(2, 4, 4, "beer", "Beer", false));
//                bg.add(new BusinessItem(2, 5, 5, "coffe", "Coffe", false));
//                bg.add(new BusinessItem(2, 6, 6, "drink", "Drinks", false));
//                list.add(bg);
//                
//                bg = new BusinessGroupItem(3, "Entertainment");
//                bg.add(new BusinessItem(3, 7, 7, "pub", "Pubs", false));
//                bg.add(new BusinessItem(3, 8, 8, "happy hour", "Happy Hour", false));
//                bg.add(new BusinessItem(3, 9, 9, "night life", "Night Life", false));
//                list.add(bg);
//                
//                bg = new BusinessGroupItem(4, "Shopping");
//                bg.add(new BusinessItem(4, 10, 10, "market", "Supermarket", false));
//                bg.add(new BusinessItem(4, 11, 11, "shopping mall", "Shopping Mall", false));
//                list.add(bg);
//                
//                oos.writeObject(list);
//            }
//        }catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//	
//	private void goImageGallery(HttpServletRequest request, HttpServletResponse response) {
//        try{
//            ObjectInputStream ois = new ObjectInputStream(request.getInputStream());
//            RecommendItem ri = (RecommendItem)ois.readObject();
//            System.out.println("[RecommendationServlet] - RecommendationItem received = " + ri.getName());
//            
//            ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
//            ArrayList<Long> list = new ArrayList<Long>();
//            for(int i = 0; i < 30; i++) {
//                list.add( Long.parseLong("" + i));
//            }
//            
//            oos.writeObject(list);
//        }catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//	
//	private void goSearchByName(HttpServletRequest request, HttpServletResponse response) {
//        try{
//            ObjectInputStream ois = new ObjectInputStream(request.getInputStream());
//            String q = request.getParameter("q").replace(" ", "+");
//            String u;
//            if ("-1".equals(request.getParameter("p"))) {//first request shouldn't send start param
//                u = String.format("http://ajax.googleapis.com/ajax/services/search/local?v=1.0&rsz=%s&q=%s", "large", q);
//            } else {
//                u = String.format("http://ajax.googleapis.com/ajax/services/search/local?v=1.0&rsz=%s&q=%s&start=%s", "large", q, request.getParameter("p"));
//            }
//            //small or large
////              String u = String.format("http://ajax.googleapis.com/ajax/services/search/local?v=1.0&rsz=%s&q=%s", "small", request.getParameter("q"));
//            System.out.println("###################################");
//            System.out.println("url = " + u);
//            System.out.println("###################################");
//            
//            URL url = new URL(u);
//            URLConnection connection = url.openConnection();
//            connection.addRequestProperty("Referer", "http://www.imstilldeveloping.com/donthaveakey.html");
//
//            String line;
//            StringBuilder builder = new StringBuilder();
//            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
//            while((line = reader.readLine()) != null) {
//                builder.append(line);
//            }
////            JSONObject json = new JSONObject(builder.toString());
//            
////            if ("-1".equals(request.getParameter("p"))) {
////                int count = json.getJSONObject("responseData").getJSONObject("cursor").getInt("estimatedResultCount");
////                ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
////                oos.writeObject((int)count/8);
////            } else {
////                LocationItem li = (LocationItem)ois.readObject();
////                ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
////                int g = (null != request.getParameter("grp") ? Integer.parseInt(request.getParameter("grp")) : -1);
////                oos.writeObject(getRI(json, li, g, false));
////            }
//            
//        }catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//   private void goOpenSearch(HttpServletRequest request, HttpServletResponse response) {
//        try{
////            ObjectInputStream ois = new ObjectInputStream(request.getInputStream());
////            LocationItem li = (LocationItem)ois.readObject();
////            String q = request.getParameter("q").replace(" ", "+");
////            String u = String.format("http://ajax.googleapis.com/ajax/services/search/local?v=1.0&rsz=%s&q=%s", "small", q);
////            //small or large
//////	            String u = String.format("http://ajax.googleapis.com/ajax/services/search/local?v=1.0&rsz=%s&q=%s", "small", request.getParameter("q"));
////            URL url = new URL(u);
////            URLConnection connection = url.openConnection();
////            connection.addRequestProperty("Referer", "http://www.imstilldeveloping.com/donthaveakey.html");
////
////            String line;
////            StringBuilder builder = new StringBuilder();
////            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
////            while((line = reader.readLine()) != null) {
////                builder.append(line);
////            }
////            JSONObject json = new JSONObject(builder.toString());
////            
////            ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
////            int g = (null != request.getParameter("grp") ? Integer.parseInt(request.getParameter("grp")) : -1);
////            oos.writeObject(getRI(json, li, g, false));
//            
//        }catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//	private void goEnhance(HttpServletRequest request, HttpServletResponse response) {
//        try{
////            ObjectInputStream ois = new ObjectInputStream(request.getInputStream());
////            LocationItem li = (LocationItem)ois.readObject();
////            double[] d = LocationUtil.createBoundingBox(li.getLatitute(), li.getLongitude(), li.getAccurancy());
////            double latN = d[0], latS= d[2], lngE= d[1], lngW= d[3];
//////            
////            String ssl = (latS + latN) / 2 + "," + (lngW + lngE) / 2;
////            String sspn = (latN - latS) / 2 + "," + (lngE - lngW) / 2;
////            
////            String q = request.getParameter("q").replace(" ", "+");
////            String u = String.format("http://ajax.googleapis.com/ajax/services/search/local?v=1.0&rsz=%s&sll=%s&sspn=%s&q=%s", "small", ssl, sspn, q);
////            //small or large
//////            String u = String.format("http://ajax.googleapis.com/ajax/services/search/local?v=1.0&rsz=%s&q=%s", "small", request.getParameter("q"));
////            URL url = new URL(u);
////            URLConnection connection = url.openConnection();
////            connection.addRequestProperty("Referer", "http://www.imstilldeveloping.com/donthaveakey.html");
////
////            String line;
////            StringBuilder builder = new StringBuilder();
////            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
////            while((line = reader.readLine()) != null) {
////                builder.append(line);
////            }
////            JSONObject json = new JSONObject(builder.toString());
////            
////            ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
////            int g = (null != request.getParameter("grp") ? Integer.parseInt(request.getParameter("grp")) : -1);
////            oos.writeObject(getRI(json, li, g, true));
//            
//        }catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//	
//	private int serverID = 0;
//	private ArrayList<RecommendItem> getRI(JSONObject json, LocationItem li, int group, boolean checkAccurance) throws Exception {
//	    ArrayList<RecommendItem> list = new ArrayList<RecommendItem>();
//	    
////	    JSONArray cur_arr = json.getJSONObject("responseData").getJSONObject("cursor").getJSONArray("pages");
////        for(int x = 0; x < cur_arr.length(); x++) {
////            JSONObject o = (JSONObject)cur_arr.get(x);
////            System.out.println("start=" + o.get("start") + ", page=" + o.get("label"));
////        }
//        
////        JSONObject json = new JSONObject(s);
//        JSONArray arr = json.getJSONObject("responseData").getJSONArray("results");
//        int length = arr.length();
//        
//        for(int i = 0; i < length; i++) {
//            JSONObject o = (JSONObject)arr.get(i);
//            float dist = LocationUtil.distanceBetween(li.getLatitute(), li.getLongitude(), Double.parseDouble(o.get("lat").toString()), Double.parseDouble(o.get("lng").toString())) / 1000;
//            if(checkAccurance && dist > li.getAccurancy()) {
//                continue;
//            }
//            
//            RecommendItem ri = new RecommendItem(RecommendItem.NEARBY);
//            if(group > -1)
//                ri.setGroup(group);
//            
//            ri.setAbout("About.com: expert guidance from real people searching the Internet for the information, goods, and services that you need to know related to your passion.");
//            
//            ri.setDistance(dist);
//            ri.setEmail("my@email.com");
//            ri.setWebsite("www.globo.com");
//            ri.setIconID(serverID);
//            ri.setImageCount(4);
//            ri.setLatitude(Double.parseDouble(o.get("lat").toString()));
//            ri.setLongitude(Double.parseDouble(o.get("lng").toString()));
//            ri.setName("" + o.get("titleNoFormatting"));
//            ri.setRating(3.4);
//            ri.setReviewCount(5367);
//            ri.setServerID(serverID);
//            
//            if(serverID++ > 10) serverID = 0;
////            ri.setWebsite(json.getUrl());
//            
//            try {
//                JSONArray add = o.getJSONArray("addressLines");
//                for(int add_i = 0; add_i < add.length(); add_i++) {
//                    ri.setAddress("" + add.get(add_i));
//                }
//                
//                JSONArray ph = o.getJSONArray("phoneNumbers");
//                for(int ph_i = 0; ph_i < ph.length(); ph_i++) {
//                    JSONObject ph_o = (JSONObject)ph.get(ph_i);
//                    ri.setPhone("" + ph_o.get("number"));
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            list.add(ri);
//        }
//	    
//        return list;
//    }
//	
//	public static byte[] getBytesFromFile(File file) {
//        byte[] bytes = null;
//        InputStream is = null;
//
//        try {
//            is = new FileInputStream(file);
//            // Get the size of the file
//            long length = file.length();
//
//            // You cannot create an array using a long type.
//            // It needs to be an int type.
//            // Before converting to an int type, check
//            // to ensure that file is not larger than Integer.MAX_VALUE.
//            if (length > Integer.MAX_VALUE) {
//                // File is too large
//            }
//
//            // Create the byte array to hold the data
//            bytes = new byte[(int) length];
//
//            // Read in the bytes
//            int offset = 0;
//            int numRead = 0;
//            while (offset < bytes.length
//                    && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
//                offset += numRead;
//            }
//
//            // Ensure all the bytes have been read in
//            if (offset < bytes.length) {
//                System.out.println("Could not completely read file " + file.getName());
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            // Close the input stream and return bytes
//            try {
//                is.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        return bytes;
//    }
}
